import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:preload_page_view/preload_page_view.dart';
import 'package:meePet/app/LocalColor.dart';
import 'package:meePet/base/BaseActivity.dart';
import 'package:meePet/manager/TabConfigManager.dart';
import 'package:meePet/ui/MainPageVM.dart';
import 'package:meePet/utils/ColorUtils.dart';
import 'package:meePet/utils/ImageUtils.dart';
import 'package:meePet/utils/ext/SizeExt.dart';
import 'package:meePet/utils/ext/StringExt.dart';

import '../base/LiveData.dart';
import '../bean/TabConfigData.dart';
import '../utils/LogUtils.dart';
import '../web/WebFragment.dart';
import '../widgets/KeepAliveWrapper.dart';
import 'fragment/ChatFragment.dart';
import 'fragment/FoundFragment.dart';

class MainPage extends BaseActivity {
  MainPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MainPageState();
  }
}

class MainPageState extends BaseActivityState<MainPage>
    with TickerProviderStateMixin {
  MainPageVM? viewModel;

  List<Tabs> _tabs = [];
  int _currentPageIndex = 0;

  Tabs? curTabInfo = null;

  PreloadPageController? _pageController = null;
  TabController? _tabController = null;

  @override
  void onCreate() {
    viewModel = Get.put(MainPageVM());
    observerToRefreshUI();
    viewModel?.requestTabData();
    super.onCreate();
  }

  void observerToRefreshUI() {
    viewModel?.tabLd.addObserver(LiveListener(change: (List<Tabs>? it) {
      if (it != null) {
        LogUtils.i("监听的数据:" + it.toString());
        _tabs = it;
        _setSelectItem(0);
        _refreshUI(needDelay: true);
      }
    }));

    LogUtils.i("页面可见，更新数据:");
  }

  void _setSelectItem(int index) {
    _onTap(index, autoRefresh: false);
    _pageChange(index, autoRefresh: false);
  }

  @override
  Widget initView(BuildContext context) {
    _pageController = PreloadPageController(initialPage: _currentPageIndex);
    _tabController = TabController(length: _tabs.length, vsync: this);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(
        /*statusBarColor: Colors.transparent,//状态栏颜色
          statusBarIconBrightness: Brightness.dark, //状态栏图标颜色
          statusBarBrightness: Brightness.dark,  //状态栏亮度
          systemStatusBarContrastEnforced: true, //系统状态栏对比度强制*/

        systemNavigationBarColor: LocalColor.colorTheme, //导航栏颜色
        systemNavigationBarIconBrightness: Brightness.dark, //导航栏图标颜色
        systemNavigationBarDividerColor: LocalColor.colorTheme, //系统导航栏分隔线颜色
        systemNavigationBarContrastEnforced: false, //系统导航栏对比度强制
      ),
      child: WillPopScope(
        onWillPop: () async =>false,
        child: getScaffold(context),
      ),
    );
    return getScaffold(context);
  }



  Widget getScaffold(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: _contentView(),
    );
  }

  Widget _contentView() {
    Widget contentView;
    contentView = Container(
      width: double.infinity,
      height: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        verticalDirection: VerticalDirection.down,
        children: [
          Expanded(child: _pageView(_tabs)),
          _getBottomTabBar(_tabs),
        ],
      ),
    );
    return contentView;
  }

  PreloadPageView _pageView(List<Tabs> tabs) {
    return PreloadPageView.builder(
      onPageChanged: _pageChange,
      controller: _pageController,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return _getFragmentByTabId(tabs[index]);
      },
      itemCount: _tabs.length,
      preloadPagesCount: 5,
    );
  }

  Widget _getFragmentByTabId(Tabs tab) {
    Widget mFragment = Text("我是${tab.title}页");
    switch (tab.tabId) {
      case TabConfigManager.found:
        mFragment = FoundFragment();
        break;
      case TabConfigManager.chat:
        mFragment = ChatFragment();
        break;
      case TabConfigManager.fetter:
        String mUrl = tab.url.urlGetParams()["h5"].toUrlDecode();
        LogUtils.i("要加载的url是啥：" + mUrl);
        mFragment = WebFragment(mUrl);
        break;
      case TabConfigManager.creation:
        String mUrl = tab.url.urlGetParams()["h5"].toUrlDecode();
        LogUtils.i("要加载的url是啥：" + mUrl);
        mFragment =  WebFragment(mUrl);
        break;
      case TabConfigManager.mine:
        String mUrl = tab.url.urlGetParams()["h5"].toUrlDecode();
        LogUtils.i("要加载的url是啥：" + mUrl);
        mFragment =  WebFragment(mUrl);
        break;
    }

    return mFragment;
  }

  Widget _getBottomTabBar(List<Tabs> tabs) {
    return SizedBox(
      width: double.infinity,
      height: null,
      child: Stack(
        children: [
          SizedBox(
            width: double.infinity,
            height: 50.sw()+MediaQuery.of(context).padding.top/3,
            child: _getBarBg(),
          ),
          TabBar(
            tabs: _getTabItems(tabs),
            onTap: _onTap,
            controller: _tabController,
            indicator: BoxDecoration(color: Colors.transparent),
            dividerHeight: 0.0,
            padding:EdgeInsets.only(
              bottom: MediaQuery.of(context).padding.top/3,
            ),
          )
        ],
      ),
    );
  }

  Widget _getBarBg() {
    if (_currentPageIndex == 0 || _currentPageIndex == 2) {
      return DecoratedBox(
          decoration: BoxDecoration(color: LocalColor.colorTheme));
    } else {
      return DecoratedBox(
          decoration: BoxDecoration(color: LocalColor.colorWhite));
    }
  }

  List<Widget> _getTabItems(List<Tabs> tabs) {
    List<Widget> viewList = [];
    tabs.forEach((item) {
      viewList.add(_getTabView(item));
    });
    return viewList;
  }

  Widget _getTabView(Tabs info) {
    if (info.tabId == curTabInfo?.tabId) {
      return getSelectTabView(info);
    } else {
      return getUnSelectedTabView(info);
    }
  }

  Widget getSelectTabView(Tabs info) {
    return SizedBox(
        width: double.infinity,
        height: 48.sw(),
        child: Align(
          child: Column(
            children: [
              ImageUtils.showNetImageWh(info.activeIcon.orEmpty(),
                  width: 25.0.sw(), height: 25.0.sw()),
              Text(
                info.title.orEmpty(),
                style: TextStyle(
                    color: ColorUtils.toColor("#865DFF"), fontSize: 11.sp()),
              )
            ],
            verticalDirection: VerticalDirection.down,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
          ),
          alignment: Alignment.center,
        ));
  }

  Widget getUnSelectedTabView(Tabs info) {
    return SizedBox(
        width: double.infinity,
        height: 48.sw(),
        child: Align(
          child: Column(
            children: [
              ImageUtils.showNetImageWh(info.icon.orEmpty(),
                  width: 25.0.sw(), height: 25.0.sw()),
              Text(
                info.title.orEmpty(),
                style: TextStyle(
                    color: ColorUtils.toColor("#9696af"), fontSize: 11.sp()),
              )
            ],
            verticalDirection: VerticalDirection.down,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
          ),
          alignment: Alignment.center,
        ));
  }

  /// bottomnaviagtionbar 和 pageview 的联动
  void _onTap(int index, {bool? autoRefresh = false}) {
    /// 过pageview的pagecontroller的animateToPage方法可以跳转
    _pageController?.jumpToPage(index);
    if (_currentPageIndex != index) {
      _currentPageIndex = index;
    }
    curTabInfo = _tabs[_currentPageIndex];
    if (autoRefresh == true) {
      _refreshUI();
    }
  }

  void _pageChange(int index, {bool? autoRefresh = true}) {
    _tabController?.animateTo(index, duration: Duration(milliseconds: 0));
    if (_currentPageIndex != index) {
      _currentPageIndex = index;
    }
    curTabInfo = _tabs[_currentPageIndex];
    if (autoRefresh == true) {
      _refreshUI();
    }
  }

  void _refreshUI({bool needDelay = false}) {
    if (needDelay) {
      Future.delayed(Duration(milliseconds: 200))
          .then((value) => {LogUtils.d("setState刷新UI"), setState(() {})});
    } else {
      LogUtils.d("setState刷新UI");
      setState(() {});
    }
  }
}
